package com.frame.system.controller;

import com.frame.common.core.security.entity.SecurityUser;
import com.frame.common.core.security.utils.TokenUtil;
import com.frame.common.core.entity.SysMenu;
import com.frame.common.core.entity.SysUser;
import com.frame.common.core.model.login.LoginBody;
import com.frame.security.service.ISysMenuService;
import com.frame.security.service.handle.SysPermissionService;
import com.frame.stant.utils.R;
import com.frame.stant.utils.ServletUtils;
import com.frame.system.service.impl.SysLoginService;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@Api(tags = "登录")
@RestController
@AllArgsConstructor
public class SysLoginController {

//    private final SysLoginService loginService;
    private final ISysMenuService menuService;
    private final SysPermissionService permissionService;
    private final TokenUtil tokenUtil;
    private final SysLoginService sysLoginService;

    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public R login(@RequestBody LoginBody loginBody) {
        String token = sysLoginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(), loginBody.getUuid());
        return R.success(token);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public R getInfo() {
        SecurityUser securityUser = tokenUtil.getCurrentUser(ServletUtils.getRequest());
        SysUser user = securityUser.getUser();
        Map<String,Object> data = Maps.newHashMap();
        data.put("user", user);
        data.put("roles", permissionService.getRolePermission(user));
        data.put("permissions", permissionService.getMenuPermission(user));
        R result = R.success(data);
        return result;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
//    @PreAuthorize("hasAuthority('')")
    @GetMapping("getRouters")
    public R getRouters() {
        SecurityUser securityUser = tokenUtil.getCurrentUser(ServletUtils.getRequest());
        SysUser user = securityUser.getUser();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(user.getUserId());
        return R.success(menuService.buildMenus(menus));
    }
}
